package com.zt.dev.siteInfoRegister.controller;

import com.zt.dev.common.ServerResponse;
import com.zt.dev.physicalequipment.pojo.PhysicalEquipmentMessage;
import com.zt.dev.siteInfoRegister.pojo.SiteUse;
import com.zt.dev.siteInfoRegister.util.ExcelUtils;
import com.zt.dev.siteInfoRegister.pojo.Site;
import com.zt.dev.siteInfoRegister.pojo.SiteInfoEnum;
import com.zt.dev.siteInfoRegister.service.SiteService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/siteInfo")
public class SiteInfoRegisterController {

    private final static String title = "场地信息记录表";

    @Autowired
    private SiteService siteService;

    /**
     * 注册，传过来的是site实体类的各个属性
     * @param site
     * @return
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public ServerResponse register(Site site){
        if(!StringUtils.isEmpty(site.getName())){
            siteService.register(site);
            return ServerResponse.createBySuccessMessage("注册成功");
        }
        return ServerResponse.createByErrorMessage("注册信息有误");
    }

    /**
     * 进入刷新查找所有场地信息
     * @return
     */
    @RequestMapping(value = "/getAll")
    @ResponseBody
    public ServerResponse getAll(@RequestParam(value = "currentPage") Integer currentPage,
                                 @RequestParam(value = "pageSize") Integer pageSize){
        List<Site> siteList = siteService.getAllPage(currentPage,pageSize);
        return ServerResponse.createBySuccess(siteList);

    }

    /**
     * 根据id查找场地信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public ServerResponse getById(@RequestParam(value = "id")Integer id){
        if (!StringUtils.isEmpty(id)){
            Site site = siteService.getById(id);
            return ServerResponse.createBySuccess(site);
        }
        return ServerResponse.createByErrorMessage("id为空");

    }

    /**
     * 根据id删除场地信息
     * @param ids
     * @return
     */
    @RequestMapping(value = "/removeById")
    @ResponseBody
    public ServerResponse removeById(@RequestParam(value = "ids") Integer[] ids){
        if (!StringUtils.isEmpty(ids)){
            for (Integer id : ids) {
                siteService.removeById(id);
            }

            return ServerResponse.createBySuccessMessage("删除成功");
        }

        return ServerResponse.createByErrorMessage("id为空");

    }

    /**
     * 修改编辑场地信息
     * @param site
     * @return
     */
    @RequestMapping(value = "/modifyById")
    @ResponseBody
    public ServerResponse modifyById(Site site){
        if (!StringUtils.isEmpty(site.getId())){
            int index = siteService.modifyById(site);
            if (index==1){
                return ServerResponse.createBySuccessMessage("修改成功");
            }
            return ServerResponse.createByErrorMessage("修改失败，请重试");

        }
        return ServerResponse.createByErrorMessage("id为空");

    }

    @RequestMapping(value = "/saveSite")
    @ResponseBody
    public ServerResponse saveSite(Site site){
        if(!StringUtils.isEmpty(site)){
            siteService.modifyById(site);
            return ServerResponse.createBySuccessMessage("保存成功");
        }
        return ServerResponse.createByErrorMessage("保存信息有误");
    }

    @RequestMapping(value = "/checkSize")
    @ResponseBody
    public ServerResponse checkSize(@RequestParam(value = "length") Integer length,
                                    @RequestParam(value   = "width") Integer width,
                                    @RequestParam(value = "id")Integer id){
        if(!StringUtils.isEmpty(length) && !StringUtils.isEmpty(width)){
            //todo  查找场地使用情况，剩余场地大小
            Site site = siteService.getById(id);
            List<SiteUse> siteUseList = siteService.getAllSiteUseById(id);
            Integer totalArea = site.getLength()*site.getWidth();

            for (SiteUse siteUse : siteUseList) {
                totalArea -= siteUse.getLength()*siteUse.getWidth();
            }
            if (totalArea>0){
                if (length>site.getLength() || width >site.getWidth()){
                    return ServerResponse.createByErrorMessage("场地长宽不符合您的场地要求");
                }else if (totalArea<length*width){
                    return ServerResponse.createByErrorMessage("场地剩余面积不足，不符合您的场地要求");
                }else return ServerResponse.createBySuccessMessage("符合要求");
            }else return ServerResponse.createByErrorMessage("场地无剩余面积，不符合您的场地要求");
        }
        return ServerResponse.createByErrorMessage("参数为空，请重试");
    }

    @RequestMapping(value = "/checkTerritory")
    @ResponseBody
    public ServerResponse checkTerritory(@RequestParam(value = "longitude") Integer longitude,
                                         @RequestParam(value = "latitude") Integer latitude){
        if(!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)){
            //todo  需要确定经纬度的范围
            Integer minArea = 50;
            Integer maxArea = 500;

            return ServerResponse.createBySuccessMessage("符合要求");
        }
        return ServerResponse.createByErrorMessage("长度或宽度为空");
    }

    @RequestMapping(value = "/checkDate")
    @ResponseBody
    public ServerResponse checkDate(@RequestParam(value = "startTime") String startTime,
                                    @RequestParam(value = "finishTime") String finishTime) throws ParseException {

        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        System.out.println(sdf.format(date));


        if(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(finishTime)){
            Date sTime = sdf.parse(startTime);
            Date eTime = sdf.parse(finishTime);
            boolean index = isEffectiveDate(date, sTime, eTime);
            if (index){
                return ServerResponse.createBySuccessMessage("时间符合要求");
            }else {
                return ServerResponse.createByErrorMessage("时间不符合要求");
            }
        }
        return ServerResponse.createByErrorMessage("请输入正确的时间");
    }

    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return false;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (begin.after(end)) {
            return false;
        } else if (date.before(begin)){
            return true;
        } else {
            return false;
        }
    }


    @RequestMapping(value = "/singleExport")
    @ResponseBody
    public ServerResponse singleExport(@RequestParam(value = "id") String id){
        if(!StringUtils.isEmpty(id)){
            //TODO:
            //导出到哪里，需要表吗
            /*int index = siteService.singleExport(id);
            if (index!=1){
                return ServerResponse.createBySuccessMessage("导出成功");
            }*/
            return ServerResponse.createBySuccessMessage("导出失败");
        }
        return ServerResponse.createByErrorMessage("请勾选一个选项");
    }


    /**
     * 导出
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportSite")
    public void exportSite(HttpServletResponse response)throws Exception{
        String fileName = title + ".xls";
        List<Site> siteList = siteService.getAll();

        String[] title1 = new String[]{"序号,1,2","场地信息,2,1","使用部队,1,1","使用具体信息,3,1","用户信息,6,1","任务信息,3,1","场地大小,4,1"};
        String[] title2 = new String[]{"场地名称", "场地地址", "使用部队", "使用状态", "开始时间", "结束时间", "用户名", "性别", "职位", "单位", "专业", "联系方式", "任务信息", "任务分配情况", "研发单位", "经度", "纬度", "长度", "宽度"};
        String[] column = new String[]{"name", "address", "troops", "state", "startTime","finishTime","userName","sex","duty","unit","major","tel","taskMsg","taskAllot","developUnit","longitude","latitude","length","width"};
        HSSFWorkbook wb = new ExcelUtils().getHSSFWorkbook(title, title1, title2, siteList, column);
        fileName = new String(fileName.getBytes(),"ISO8859-1");
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        response.addHeader("Pargam","no-cache");
        response.addHeader("Cache-Control","no-cache");
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }



    @RequestMapping(value = "/singleAdd")
    @ResponseBody
    public ServerResponse singleAdd(PhysicalEquipmentMessage physicalEquipmentMessage){
        if(!StringUtils.isEmpty(physicalEquipmentMessage)){
            int index = siteService.addPhysicalEquipmentMessage(physicalEquipmentMessage);
            if (index==1){
                return ServerResponse.createBySuccessMessage("导入成功");
            }
            return ServerResponse.createBySuccessMessage("导入失败");
        }
        return ServerResponse.createByErrorMessage("请添加试验资源");
    }

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/importSite")
    public ServerResponse importSite(MultipartFile file)throws Exception{
        ExcelUtils excelUtil = new ExcelUtils(SiteInfoEnum.objMap);
        try {
            saveData(excelUtil,file);

            if(excelUtil.getRowNum() != excelUtil.getTotalRowNum()){
                saveData(excelUtil,file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("导入数据时出现错误！");
        }
        return ServerResponse.createBySuccess("导入成功");
    }


    private void saveData(ExcelUtils excelUtil,MultipartFile file) throws Exception {
        List<Object> list = excelUtil.getDataFromExcel(file, Site.class);
        for(int i =0;i<list.size();i++){
            Site site = (Site) list.get(i);

            siteService.register(site);
        }
        System.gc();
    }
}
